﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentValidation;
using Micrhard.FMCG.Server.Models;
using Micrhard.FMCG.Server.Msg;
using FluentValidation.Results;
using Micrhard.FMCG.Server.Interface;
using Microhard.Core;

namespace Micrhard.FMCG.Server.Validator
{
    public class ProductMappingKAPrdModelValidator : AbstractValidator<PrductMappingKAPrdModel>
    {
        public ProductMappingKAPrdModelValidator()
        {
            RuleSet("Insert", () =>
            {
                RuleFor(u => u.KAID).NotEmpty().WithMessage(PrdMappingKAPrdMsg.NeedKA).When(r => r.PrdDepID == Guid.Empty);
                RuleFor(u => u.ProductID).NotEmpty().WithMessage(PrdMappingKAPrdMsg.NeedPrd).When(r => r.PrdDepID == Guid.Empty);
                RuleFor(u => u.CustomerCode).NotEmpty().WithMessage(PrdMappingKAPrdMsg.NeedCustomPrdCode).When(r => r.PrdDepID == Guid.Empty);
                RuleFor(u => u.CustomerCode).Length(1, 50).WithMessage(PrdMappingKAPrdMsg.CustomPrdCodeMaxLength).When(r => r.PrdDepID == Guid.Empty);
                Custom(u =>
                {
                    IPrdMapKAPrd ka = IoC.Resolve<IPrdMapKAPrd>();
                    if (ka.IsCustomeCodeInUsing(u.CustomerCode, u.KAID))
                    {
                        return new ValidationFailure("CustomerCode", PrdMappingKAPrdMsg.CodeIsInUsing);
                    }
                    if (ka.IsPrdIsInUsing(u.ProductID, u.KAID))
                    {
                        return new ValidationFailure("ProductID", PrdMappingKAPrdMsg.PrdIsInUsing);
                    }
                    return null;
                });
            });

            RuleSet("Update", () =>
            {
                RuleFor(u => u.CustomerCode).NotEmpty().WithMessage(PrdMappingKAPrdMsg.NeedCustomPrdCode);
                RuleFor(u => u.CustomerCode).Length(1, 50).WithMessage(PrdMappingKAPrdMsg.CustomPrdCodeMaxLength);

                Custom(u =>
                {
                    IPrdMapKAPrd ka = IoC.Resolve<IPrdMapKAPrd>();
                    if (ka.IsCustomeCodeInUsing(u.CustomerCode, u.KAID))
                    {
                        return new ValidationFailure("CustomerCode", PrdMappingKAPrdMsg.CodeIsInUsing);
                    }
                    return null;
                });
            });
        }
    }
}
